<template>
  <a-modal
    title="操作"
    style="top: 20px;"
    :width="800"
    v-model="visible"
    :maskClosable="false"
    destroyOnClose
    :confirmLoading="confirmLoading"
    @ok="handleSubmit">
    <a-form :form="form">
      <a-form-item style="display:none"><a-input v-decorator="['id']" /></a-form-item>
      <a-form-item :labelCol="{ span: 24 }" :wrapperCol="{ span: 24 }" label="地图范围">
        <baidu-map
          @click="mapclick"
          @moving="syncCenterAndZoom"
          @moveend="syncCenterAndZoom"
          @zoomend="syncCenterAndZoom"

          scroll-wheel-zoom
          class="map"
          :zoom="mapZoom"
          :center="mapCenter"
        >
          <bm-control>
            <a-button v-if="this.polygonPath.length == 0" type="primary" icon="radius-setting" @click="createPolygonPath">建立范围</a-button>
            <a-button v-else type="danger" icon="delete" @click="clearPolygonPath">清除范围</a-button>
          </bm-control>
          <bm-polygon :path="polygonPath" strokeStyle="dashed" @lineupdate="updatePolygonPath" :editing="true"></bm-polygon>
        </baidu-map>
        <a-input
          style="display: none;"
          placeholder="地图范围"
          v-decorator="['map', { rules: [{ required: true, message: '请选择地图范围' }, { min: 100, message: '请选择地图范围' }] }]"
        />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务名称">
        <a-input placeholder="任务名称" v-decorator="['name', { rules: [{ required: true, message: '请输入任务名称' }] }]" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务时间">
        <a-range-picker
          :showTime="{ format: 'HH:mm:ss', hideDisabledOptions: true, defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] }"
          :format="dateFormat"
          style="width: 100%"
          @ok="onOk"
          v-decorator="['buildTime', { rules: [{ required: true, message: '请选择起止日期' }] }]"
        />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="系部">
        <a-select placeholder="请选择系部" @change="selectDept" v-decorator="['deptId']" allowClear>
          <a-select-option v-for="(b, index) in deptList" :key="index" :value="b.deptId">{{ b.deptName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="年级">
        <a-select mode="multiple" placeholder="请选择年级" @change="selectGrade" v-decorator="['grades']" allowClear>
          <a-select-option v-for="(b, index) in gradeList" :key="index" :value="b.year">{{ b.yearName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="教育层次">
        <a-select mode="multiple" placeholder="请选择教育层次" @change="selectEducationalLevel" v-decorator="['educationalLevels']" allowClear>
          <a-select-option v-for="(b, index) in educationalLevelList" :key="index" :value="b.dictValue">{{ b.dictLabel }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="班级">
        <a-select mode="multiple" placeholder="请选择班级" v-decorator="['classesIds']" allowClear>
          <a-select-option v-for="(b, index) in classesActiveList" :key="index" :value="b.classesId">{{ b.classesName }}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { saveSysSignJob } from '@/api/signJob'
import { getClassesList } from '@/api/classes'
import { getDeptTeachList } from '@/api/system'
import { bdTogcj, gcjTobd } from '@/utils/mapUtil.js'
import { getGradeYearList } from '@/api/gradeYear'
import { getDictArray } from '@/utils/dict'
import moment from 'moment'
import pick from 'lodash.pick'
export default {
  name: 'SignJobModal',
  props: {},
  components: {},
  data () {
    return {
      mapObj: null,
      dateFormat: 'YYYY-MM-DD HH:mm:ss',
      visible: false,
      mapCenter: {
        lng: 110.584363,
        lat: 40.598576
      },
      mapZoom: 15,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      mdl: {},
      polygonPath: [],
      form: this.$form.createForm(this),

      deptList: [],
      gradeList: [],
      classesList: [],
      educationalLevelList: [],
      grades: [],
      deptId: '',
      educationalLevels: []
    }
  },
  beforeCreate () {},
  created () {
    getDeptTeachList().then(res => {
      if (res.code === 0) {
        this.deptList = res.data
      }
    })
    getGradeYearList().then(res => {
      this.gradeList = res
    })
    getClassesList().then(res => {
      this.classesList = res
    })
    getDictArray('st_educational_level').then(res => {
      this.educationalLevelList = res
    })
  },
  computed: {
    classesActiveList () {
      return this.classesList.filter(item => {
        var flag = true
        if (flag && this.deptId) {
          flag = item.deptId === this.deptId
        }
        if (flag && this.grades.length > 0) {
          flag = this.grades.includes(item.grade)
        }
        if (flag && this.educationalLevels.length > 0) {
          flag = this.educationalLevels.includes(item.educationalLevel)
        }
        return flag
      })
    }
  },
  watch: {
    polygonPath (value) {
      const tmp = value.map(item => {
        const gcjPoint = bdTogcj(item.lat, item.lng)
        return {
          latitude: gcjPoint[0],
          longitude: gcjPoint[1]
        }
      })
      this.$nextTick(() => {
        this.form.setFieldsValue({
          map: JSON.stringify(tmp)
        })
      })
    }
  },
  methods: {
    selectGrade (value) {
      this.grades = value
    },
    selectDept (value) {
      this.deptId = value
    },
    selectEducationalLevel (value) {
      this.educationalLevels = value
    },
    moment,
    createPolygonPath () {
      // 在屏幕中间创建一个初始选区
      const step = 0.003
      this.polygonPath.push({
        lng: this.mapCenter.lng - step,
        lat: this.mapCenter.lat - step
      })
      this.polygonPath.push({
        lng: this.mapCenter.lng - step,
        lat: this.mapCenter.lat + step
      })
      this.polygonPath.push({
        lng: this.mapCenter.lng + step,
        lat: this.mapCenter.lat - step
      })
    },
    clearPolygonPath () {
      this.polygonPath = []
    },
    syncCenterAndZoom (e) {
      const { lng, lat } = e.target.getCenter()
      this.mapCenter.lng = lng
      this.mapCenter.lat = lat
      this.mapZoom = e.target.getZoom()
    },
    updatePolygonPath (e) {
      this.polygonPath = e.target.getPath()
    },
    add () {
      this.polygonPath = []
      this.mapCenter = {
        lng: 110.584363,
        lat: 40.598576
      }
      this.mapZoom = 15
      this.form.resetFields()
      this.edit({ id: 0 })
    },
    edit (record) {
      this.mdl = Object.assign(record)
      this.visible = true
      if (this.mdl.startTime && this.mdl.finishTime) {
        this.mdl.buildTime = [moment(this.mdl.startTime, this.dateFormat), moment(this.mdl.finishTime, this.dateFormat)]
      }
      if (!this.mdl.deptId) {
        this.mdl.deptId = undefined
      }
      this.deptId = this.mdl.deptId
      this.mdl.grades = typeof this.mdl.grades === 'string' ? this.mdl.grades.split(',').map(item => parseInt(item)) : this.mdl.grades ? this.mdl.grades : []
      this.grades = this.mdl.grades
      this.mdl.classesIds = typeof this.mdl.classesIds === 'string' ? this.mdl.classesIds.split(',') : this.mdl.classesIds ? this.mdl.classesIds : []
      this.mdl.educationalLevels = typeof this.mdl.educationalLevels === 'string' ? this.mdl.educationalLevels.split(',') : this.mdl.educationalLevels ? this.mdl.educationalLevels : []
      this.educationalLevels = this.mdl.educationalLevels

      if (this.mdl.map) {
        const map = JSON.parse(this.mdl.map)
        let centerLat = 0
        let centerLng = 0

        this.polygonPath = map.map(item => {
          const bdPoint = gcjTobd(item.latitude, item.longitude)
          centerLat += bdPoint[0]
          centerLng += bdPoint[1]
          return {
            lat: bdPoint[0],
            lng: bdPoint[1]
          }
        })
        this.mapCenter = {
          lat: centerLat / this.polygonPath.length,
          lng: centerLng / this.polygonPath.length
        }
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'name', 'buildTime', 'map', 'deptId', 'grades', 'educationalLevels', 'classesIds'))
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        values.startTime = values.buildTime[0].format(this.dateFormat)
        values.finishTime = values.buildTime[1].format(this.dateFormat)
        values.classesIds = values.classesIds.length ? values.classesIds.join(',') : undefined
        values.grades = values.grades.length ? values.grades.join(',') : undefined
        values.educationalLevels = values.educationalLevels.length ? values.educationalLevels.join(',') : undefined
        if (!err) {
          this.confirmLoading = true
          saveSysSignJob(values)
            .then(res => {
              if (res.code === 0) {
                this.$message.success('保存成功')
                this.$emit('ok')
                this.visible = false
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(() => {
              this.$message.error('系统错误，请稍后再试')
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    }
  }
}
</script>
<style>
.map {
  width: 100%;
  height: 300px;
}
</style>
